//
//  WZPBaseThemeViewController.m
//  WZPItem
//
//  Created by 王王喆平 on 16/7/21.
//  Copyright © 2016年 UI. All rights reserved.
//

//
//  WZPAllViewController.m
//  WZPItem
//
//  Created by 王王喆平 on 16/7/13.
//  Copyright © 2016年 UI. All rights reserved.
//

#import "WZPBaseThemeViewController.h"

#import "WZPThemeCell.h"
#import <MJExtension/MJExtension.h>
#import <AFNetworking.h>
#import "WZPThemeItem.h"
#import "WZPThemeModel.h"
#import "WZPFootRreshView.h"
#import "WZPBtoomRreshView.h"
#import <MJRefresh/MJRefresh.h>
#import "WZPEssenceController.h"


static NSString *  ID = @"cell";

@interface WZPBaseThemeViewController ()

// 保存所有视图模型
@property(nonatomic,strong) NSMutableArray * themViewModel;

@property(nonatomic,strong) WZPFootRreshView * footView;
@property(nonatomic,strong) WZPBtoomRreshView * headView;
@property(nonatomic,assign) NSInteger maxtime;
@property(nonatomic,strong) AFHTTPSessionManager * mar;

@end

@implementation WZPBaseThemeViewController
-(AFHTTPSessionManager *)mar{
    if (_mar == nil) {
        _mar  = [AFHTTPSessionManager manager];
    }
    return _mar;
    
}
-(NSMutableArray *) themViewModel{
    if (_themViewModel == nil) {
        _themViewModel = [NSMutableArray array];
    }
    return _themViewModel;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 注册cell
    [self.tableView registerClass:[WZPThemeCell class] forCellReuseIdentifier:ID];
    // 让出 标题位置,增加额外滚动区域
    self.tableView.contentInset = UIEdgeInsetsMake(64 + 34, 0, 0, 0);
    // 加载数据
    [self loadData];
    self.tableView.separatorStyle = UITableViewCellEditingStyleNone;
    self.tableView.backgroundColor = [UIColor lightGrayColor];
    
    [self setupRreshView];
}
-(void)setupRreshView{
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    // 自动隐藏下拉控件
    header.automaticallyChangeAlpha = YES;
    self.tableView.mj_header = header;
    
    MJRefreshAutoNormalFooter * footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.automaticallyHidden = YES;
    self.tableView.mj_footer = footer;
    
    
}
/*-(void)setupHeadViewRreshView{
 // 下拉直接添加到顶不上方
 WZPBtoomRreshView * headView = [WZPBtoomRreshView headView];
 headView.wzp_width = WZPScreenW;
 headView.wzp_y = -headView.wzp_height;
 [self.tableView addSubview:headView];
 _headView = headView;
 }
 
 -(void)setupFootRreshView{
 
 WZPFootRreshView * footView = [WZPFootRreshView footView];
 self.tableView.tableFooterView = footView;
 footView.hidden = YES;
 _footView = footView;
 
 }
 // 拖动时调用
 -(void)scrollViewDidScroll:(UIScrollView *)scrollView{
 
 [self dealFootView];
 [self dealHeadView];
 
 }
 //当用户停止拖动时调用
 -(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
 CGFloat offsetY = self.tableView.contentOffset.y;
 if (offsetY <= -(self.tableView.contentInset.top + _headView.wzp_height)) {
 // 判断是否正在刷新,如再刷新就不再次刷新
 if (_headView.isRreshView == YES) return;
 [self loadData];
 
 _headView.isRreshView = YES;
 
 }
 
 }
 
 -(void)dealHeadView{
 if (self.themViewModel.count == 0) return;
 // 判断什么时候显示下拉控件
 CGFloat offsetY = self.tableView.contentOffset.y;
 if (offsetY <= - (self.tableView.contentInset.top + _headView.wzp_height)) {
 _headView.isVisable = YES;
 }else{
 _headView.isVisable = NO;
 
 }
 
 }
 -(void)dealFootView{
 
 if (self.themViewModel.count == 0)return;
 // 判断上下拉控件什么时候完全显示
 CGFloat offsetY = self.tableView.contentOffset.y;
 if (offsetY >= self.tableView.contentSize.height + self.tableView.contentInset.bottom - WZPScreenH) {
 //判断是否正在加载数据
 if (_footView.isRreshView)  return;
 
 [self loadMoreData];
 
 _footView.isRreshView = YES;
 
 }
 }*/
#pragma mamrk 加载更多数据
-(void)loadMoreData{
    // 取消下拉请求
    [self.mar.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    // 创建会话对象
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    // 请求拼接参数
    NSMutableDictionary * parameters = [NSMutableDictionary dictionary];
//    parameters[@"a"] = @"list";
    NSString *a = @"newList";
    if ([self.parentViewController isKindOfClass:[WZPEssenceController class]]) {
        a = @"list";
    }
    parameters[@"a"] = a;
    parameters[@"c"] = @"data";
    parameters[@"type"] = @(self.type);
    parameters[@"maxtime"] = @(_maxtime);
    [manager GET:WZPHtp parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        // 更新上拉刷新状态
        //        _footView.isRreshView = NO;
        // 结束上拉刷新
        [self.tableView.mj_footer endRefreshing];
        
        // 记载上一页最大值
        _maxtime = [responseObject[@"info"][@"maxtime"] integerValue];
        // 获取数组
        NSArray * array = responseObject[@"list"];
        
        NSArray * itemlist = [WZPThemeItem mj_objectArrayWithKeyValuesArray:array];
        // 转视图模型开发
        for (WZPThemeItem * item in itemlist) {
            // 创建视图模型
            WZPThemeModel * model = [[WZPThemeModel alloc]init];
            model.item = item;
            [self.themViewModel addObject:model];
        }
        
        
        // 刷新表格
        [self.tableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
    
}
#pragma mamrk 加载数据

-(void)loadData{
    
    // 创建会话对象
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    // 请求拼接参数
    NSMutableDictionary * parameters = [NSMutableDictionary dictionary];
//    parameters[@"a"] = @"list";
    NSString *a = @"newList";
    if ([self.parentViewController isKindOfClass:[WZPEssenceController class]]) {
        a = @"list";
    }
    parameters[@"a"] = a;
    parameters[@"c"] = @"data";
    parameters[@"type"] = @(self.type);

    [manager GET:WZPHtp parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        _footView.hidden = NO;
        //        _headView.hidden = NO;
        
        [self.tableView.mj_header  endRefreshing];
        
        _maxtime = [responseObject[@"info"][@"maxtime"] integerValue];
        
        // 获取数组
        NSArray * array = responseObject[@"list"];
        
        NSArray * itemlist = [WZPThemeItem mj_objectArrayWithKeyValuesArray:array];
        // 转视图模型开发
        for (WZPThemeItem * item in itemlist) {
            // 创建视图模型
            WZPThemeModel * model = [[WZPThemeModel alloc]init];
            model.item = item;
            [self.themViewModel addObject:model];
        }
        
        
        // 刷新表格
        [self.tableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
    
}

#pragma mark - Table view data source
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _themViewModel.count;
    
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WZPThemeCell * cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    
    cell.model = _themViewModel[indexPath.row];
    
    return cell;
    
}
// 返回cell 高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [_themViewModel[indexPath.row] cellH] + 10;
    
}

@end
